<template>
  <div class="permission-management">
    <a-card>
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" class="search-form">
        <a-form-item :label="t('permission.permissionName')">
          <a-input
            v-model:value="queryParams.permissionName"
            :placeholder="t('permission.permissionNamePlaceholder')"
            allow-clear
          />
        </a-form-item>
        <a-form-item :label="t('permission.permissionCode')">
          <a-input
            v-model:value="queryParams.permissionCode"
            :placeholder="t('permission.permissionCodePlaceholder')"
            allow-clear
          />
        </a-form-item>
        <a-form-item :label="t('permission.permissionType')">
          <a-select
            v-model:value="queryParams.permissionType"
            :placeholder="t('permission.permissionTypePlaceholder')"
            allow-clear
          >
            <a-select-option :value="PermissionType.MENU">{{ t('permission.type.menu') }}</a-select-option>
            <a-select-option :value="PermissionType.BUTTON">{{ t('permission.type.button') }}</a-select-option>
            <a-select-option :value="PermissionType.API">{{ t('permission.type.api') }}</a-select-option>
            <a-select-option :value="PermissionType.DATA">{{ t('permission.type.data') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="t('common.status')">
          <a-select
            v-model:value="queryParams.status"
            :placeholder="t('common.statusPlaceholder')"
            allow-clear
          >
            <a-select-option :value="1">{{ t('common.normal') }}</a-select-option>
            <a-select-option :value="0">{{ t('common.disabled') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              {{ t('common.search') }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon><redo-outlined /></template>
              {{ t('common.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            {{ t('common.add') }}
          </a-button>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="permissionList"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 1200 }"
        :row-key="record => record.id"
        :expandable="{
          defaultExpandAllRows: true,
          expandRowByClick: true,
          childrenColumnName: 'children'
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'permissionType'">
            <a-tag :color="getPermissionTypeColor(record.permissionType)">
              {{ getPermissionTypeText(record.permissionType) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? t('common.normal') : t('common.disabled') }}
            </a-tag>
          </template>
          <template v-if="column.key === 'icon'">
            <span v-if="record.icon">{{ record.icon }}</span>
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                {{ t('common.edit') }}
              </a-button>
              <a-button type="link" size="small" @click="handleAddSub(record)">
                {{ t('common.add') }}
              </a-button>
              <a-popconfirm
                :title="t('common.confirmDelete')"
                :ok-text="t('common.confirm')"
                :cancel-text="t('common.cancel')"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  {{ t('common.delete') }}
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :width="600"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item :label="t('permission.parentPermission')" name="parentId">
          <a-tree-select
            v-model:value="formData.parentId"
            :tree-data="permissionTree"
            :placeholder="t('permission.parentPermissionPlaceholder')"
            :field-names="{ label: 'permissionName', value: 'id', children: 'children' }"
            allow-clear
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item :label="t('permission.permissionName')" name="permissionName">
          <a-input
            v-model:value="formData.permissionName"
            :placeholder="t('permission.permissionNamePlaceholder')"
          />
        </a-form-item>
        <a-form-item :label="t('permission.permissionCode')" name="permissionCode">
          <a-input
            v-model:value="formData.permissionCode"
            :placeholder="t('permission.permissionCodePlaceholder')"
          />
        </a-form-item>
        <a-form-item :label="t('permission.permissionType')" name="permissionType">
          <a-select
            v-model:value="formData.permissionType"
            :placeholder="t('permission.permissionTypePlaceholder')"
          >
            <a-select-option :value="PermissionType.MENU">{{ t('permission.type.menu') }}</a-select-option>
            <a-select-option :value="PermissionType.BUTTON">{{ t('permission.type.button') }}</a-select-option>
            <a-select-option :value="PermissionType.API">{{ t('permission.type.api') }}</a-select-option>
            <a-select-option :value="PermissionType.DATA">{{ t('permission.type.data') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="t('permission.path')" name="path" v-if="formData.permissionType === PermissionType.MENU">
          <a-input
            v-model:value="formData.path"
            :placeholder="t('permission.pathPlaceholder')"
          />
        </a-form-item>
        <a-form-item :label="t('permission.component')" name="component" v-if="formData.permissionType === PermissionType.MENU">
          <a-input
            v-model:value="formData.component"
            :placeholder="t('permission.componentPlaceholder')"
          />
        </a-form-item>
        <a-form-item :label="t('permission.icon')" name="icon" v-if="formData.permissionType === PermissionType.MENU">
          <a-input
            v-model:value="formData.icon"
            :placeholder="t('permission.iconPlaceholder')"
          />
        </a-form-item>
        <a-form-item :label="t('permission.sort')" name="sort">
          <a-input-number
            v-model:value="formData.sort"
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item :label="t('common.status')" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">{{ t('common.normal') }}</a-radio>
            <a-radio :value="0">{{ t('common.disabled') }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  MenuOutlined,
  UserOutlined,
  TeamOutlined,
  SettingOutlined,
  AppstoreOutlined,
  DashboardOutlined,
  FileOutlined,
  FolderOutlined
} from '@ant-design/icons-vue'
import type { PermissionInfo, PermissionQuery, PermissionTreeNode, MenuTreeNode } from '@/types/permission.type'
import { PermissionType } from '@/types/permission.type'
import {
  getPermissionList,
  getPermissionTree,
  getMenuTree,
  createPermission,
  updatePermission,
  deletePermission
} from '@/api/permission'

const { t } = useI18n()

// 查询参数
const queryParams = reactive<PermissionQuery>({
  permissionName: '',
  permissionCode: '',
  permissionType: undefined,
  status: undefined,
  current: 1,
  size: 10
})

// 表格列定义
const columns = [
  {
    title: t('permission.permissionName'),
    dataIndex: 'permissionName',
    key: 'permissionName',
    width: 200,
    fixed: 'left'
  },
  {
    title: t('permission.permissionCode'),
    dataIndex: 'permissionCode',
    key: 'permissionCode',
    width: 200
  },
  {
    title: t('permission.permissionType'),
    dataIndex: 'permissionType',
    key: 'permissionType',
    width: 120
  },
  {
    title: t('permission.path'),
    dataIndex: 'path',
    key: 'path',
    width: 200
  },
  {
    title: t('permission.component'),
    dataIndex: 'component',
    key: 'component',
    width: 200
  },
  {
    title: t('permission.icon'),
    dataIndex: 'icon',
    key: 'icon',
    width: 100
  },
  {
    title: t('permission.sort'),
    dataIndex: 'sort',
    key: 'sort',
    width: 100
  },
  {
    title: t('common.status'),
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: t('common.action'),
    key: 'action',
    fixed: 'right',
    width: 150
  }
]

// 权限列表数据
const permissionList = ref<PermissionTreeNode[]>([])
const permissionTree = ref<PermissionTreeNode[]>([])
const menuTree = ref<MenuTreeNode[]>([])
const loading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const modalVisible = ref(false)
const modalTitle = ref('')
const formData = reactive<Partial<PermissionInfo>>({
  parentId: undefined,
  permissionName: '',
  permissionCode: '',
  permissionType: PermissionType.MENU,
  menuId: undefined,
  path: '',
  component: '',
  icon: '',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  permissionName: [{ required: true, message: t('permission.permissionNameRequired') }],
  permissionCode: [{ required: true, message: t('permission.permissionCodeRequired') }],
  permissionType: [{ required: true, message: t('permission.permissionTypeRequired') }],
  path: [{ required: true, message: t('permission.pathRequired') }],
  component: [{ required: true, message: t('permission.componentRequired') }],
  sort: [{ required: true, message: t('permission.sortRequired') }],
  status: [{ required: true, message: t('common.statusRequired') }]
}

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const res = await getPermissionTree()
    // 确保返回的数据是数组
    if (Array.isArray(res)) {
      permissionList.value = res.map(item => ({
        ...item,
        key: item.id,
        children: item.children || []
      }))
      permissionTree.value = permissionList.value
    } else {
      permissionList.value = []
      permissionTree.value = []
    }
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
    permissionList.value = []
    permissionTree.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchPermissionList()
}

// 重置
const handleReset = () => {
  queryParams.permissionName = ''
  queryParams.permissionCode = ''
  queryParams.permissionType = undefined
  queryParams.status = undefined
  fetchPermissionList()
}

// 新增权限
const handleAdd = () => {
  modalTitle.value = t('permission.add')
  Object.assign(formData, {
    parentId: undefined,
    permissionName: '',
    permissionCode: '',
    permissionType: PermissionType.MENU,
    menuId: undefined,
    path: '',
    component: '',
    icon: '',
    sort: 0,
    status: 1
  })
  modalVisible.value = true
}

// 编辑权限
const handleEdit = (record: PermissionInfo) => {
  modalTitle.value = t('permission.edit')
  Object.assign(formData, record)
  modalVisible.value = true
}

// 新增子权限
const handleAddSub = (record: PermissionInfo) => {
  modalTitle.value = t('permission.addSub')
  Object.assign(formData, {
    parentId: record.id,
    permissionName: '',
    permissionCode: '',
    permissionType: PermissionType.MENU,
    menuId: undefined,
    path: '',
    component: '',
    icon: '',
    sort: 0,
    status: 1
  })
  modalVisible.value = true
}

// 删除权限
const handleDelete = async (record: PermissionInfo) => {
  try {
    await deletePermission(record.id)
    message.success(t('common.success'))
    fetchPermissionList()
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  }
}

// 弹窗确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    const submitData = {
      id: formData.id || 0,
      parentId: formData.parentId || 0,
      permissionName: formData.permissionName,
      permissionCode: formData.permissionCode,
      permissionType: formData.permissionType,
      menuId: formData.menuId || 0,
      path: formData.path || '',
      component: formData.component || '',
      icon: formData.icon || '',
      sort: formData.sort || 0,
      status: formData.status
    }
    
    if (formData.id) {
      await updatePermission(submitData)
      message.success(t('common.success'))
    } else {
      await createPermission(submitData)
      message.success(t('common.success'))
    }
    modalVisible.value = false
    fetchPermissionList()
  } catch (error: any) {
    if (error.errorFields) {
      return
    }
    message.error(error.message || t('common.failed'))
  }
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 获取权限类型文本
const getPermissionTypeText = (type: PermissionType) => {
  const map = {
    [PermissionType.MENU]: '菜单',
    [PermissionType.BUTTON]: '按钮',
    [PermissionType.API]: '接口',
    [PermissionType.DATA]: '数据'
  }
  return map[type]
}

// 获取权限类型颜色
const getPermissionTypeColor = (type: PermissionType) => {
  const map = {
    [PermissionType.MENU]: 'blue',
    [PermissionType.BUTTON]: 'green',
    [PermissionType.API]: 'orange',
    [PermissionType.DATA]: 'purple'
  }
  return map[type]
}

onMounted(() => {
  fetchPermissionList()
})
</script>

<style lang="less" scoped>
.permission-management {
  .search-form {
    margin-bottom: 16px;
  }

  .table-operations {
    margin-bottom: 16px;
  }
}
</style> 